﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FrenzDenWebSite.Business;

namespace FrenzDenWebSite
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies[SiteConstants.COOKIESTRINGPROFILE] != null)
            {
                Response.Redirect("~/Home.aspx");
            }

            if (Request.QueryString.AllKeys.Contains("showmsg"))
            {
                MessageBox msgbox = new MessageBox("Please login!");
                msgboxpanel.InnerHtml = msgbox.ReturnObject();
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            bool valid = false;
            ProfileItem profile = new ProfileItem();
            using (DenStoreDataContext dataContext = new DenStoreDataContext())
            {
                var result = from obj in dataContext.ProfileInfos
                             join m in dataContext.MediaLibraries on obj.ProfilePicID equals m.MediaID
                             where obj.EmailID == txtLoginEmail.Text.ToLower().Trim() && obj.Password == txtLoginPassword.Text
                             select new {obj.ProfileID, obj.FullName, obj.Gender, m.MediaPath };
                
                foreach (var item in result)
                {
                    profile.ProfileID = item.ProfileID;
                    profile.Name = item.FullName;
                    profile.Gender = item.Gender;
                    profile.ImageUrl = string.Format("Media/Pic/{0}", item.MediaPath);

                    valid = true;
                }
            }

            if (valid)
            {
                Response.Cookies.Add(new HttpCookie(SiteConstants.COOKIESTRINGPROFILE, SiteCommon.EncryptSession(profile)));
                Response.Cookies.Add(new HttpCookie(SiteConstants.COOKIESTRINGPROFILEID, profile.ProfileID.ToString()));
                Response.Cookies[0].Expires = DateTime.Now.AddHours(1);
                Response.Cookies[1].Expires = DateTime.Now.AddHours(1);
                if (Request.QueryString.AllKeys.Contains("prev"))
                {
                    Response.Redirect(string.Format("~/{0}.aspx", Request.QueryString["prev"]));
                }
                else
                {
                    Response.Redirect("~/Home.aspx");
                }
            }
            else
            {
                MessageBox msgbox = new MessageBox("Invalid login! Please try again.");
                msgboxpanel.InnerHtml = msgbox.ReturnObject();
            }
        }
    }
}